import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { UsersService } from '../../users/users.service';

@Injectable()
export class PermissionsGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private usersService: UsersService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const requiredPermissions = this.reflector.get<string[]>(
      'permissions',
      context.getHandler(),
    );
    
    if (!requiredPermissions) {
      return true;
    }
    
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    
    if (!user) {
      return false;
    }
    
    // 获取用户的所有权限
    const userWithPermissions = await this.usersService.findOneWithPermissions(user.userId);
    
    // 检查用户是否拥有所需权限
    if (!userWithPermissions) {
      return false;
    }

    return requiredPermissions.some(permission => 
      (userWithPermissions.permissions as string[]).includes(permission)
    );
  }
} 